﻿using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using PagedList;
using Image = JinRi.Services.Domains.Image;

namespace JinRiAdmin.WebHost.Controllers
{
    public class ImageController : BaseController
    {
        public ActionResult Upload(HttpPostedFileBase file)
        {
            var bytes = new byte[file.InputStream.Length];
            file.InputStream.Read(bytes, 0,file.ContentLength);
            var image = Service.AddImage(bytes);
            return Json(image.Id);
        }

        [AllowAnonymous]
        public ActionResult Raw(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var image = Service.Find<Image>(id.Value);
            if (image == null)
            {
                return HttpNotFound();
            }

            Response.Cache.SetExpires(DateTime.Now.AddYears(1));
            Response.Cache.SetMaxAge(new TimeSpan(365,0,0,0));
            Response.Cache.SetCacheability(HttpCacheability.Public);
            return File(image.Bytes, "image/jpeg");
        }

        public ActionResult Thumb(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var image = Service.Find<Image>(id.Value);
            if (image == null)
            {
                return HttpNotFound();
            }

            Response.Cache.SetExpires(DateTime.Now.AddYears(1));
            Response.Cache.SetMaxAge(new TimeSpan(365, 0, 0, 0));
            Response.Cache.SetCacheability(HttpCacheability.Public);
            return File(MakeThumbnail(image.Bytes, 200, 0, "W", "png"), "image/png");
        }

        public static byte[] MakeThumbnail(byte[] bytes, int width, int height, string mode, string imageType)
        {
            var ret = new MemoryStream();
            var originalImage = System.Drawing.Image.FromStream(new MemoryStream(bytes));
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）　　
                    break;
                case "W"://指定宽，高按比例　　　　　　　　　　   
                    toheight = originalImage.Height * width / originalImage.Width;
                    if (width > ow)
                    {
                        return bytes;
                    }
                    break;
                case "H"://指定高，宽按比例   
                    if (height > oh)
                    {
                        return bytes;
                    }
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）　　　　　　　　   
                    if (originalImage.Width / (double)originalImage.Height > towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
            }
            //新建一个bmp图片   
            var bitmap = new Bitmap(towidth, toheight);
            //新建一个画板   
            Graphics g = Graphics.FromImage(bitmap);
            //设置高质量插值法   
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度   
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充   
            g.Clear(Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分   
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
               new Rectangle(x, y, ow, oh),
               GraphicsUnit.Pixel);
            try
            {
                //以jpg格式保存缩略图   
                switch (imageType.ToLower())
                {
                    case "gif":
                        bitmap.Save(ret, System.Drawing.Imaging.ImageFormat.Gif);
                        break;
                    case "jpg":
                        bitmap.Save(ret, System.Drawing.Imaging.ImageFormat.Jpeg);
                        break;
                    case "bmp":
                        bitmap.Save(ret, System.Drawing.Imaging.ImageFormat.Bmp);
                        break;
                    case "png":
                        bitmap.Save(ret, System.Drawing.Imaging.ImageFormat.Png);
                        break;
                    default:
                        bitmap.Save(ret, System.Drawing.Imaging.ImageFormat.Jpeg);
                        break;
                }
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
            return ret.GetBuffer();
        }

        public ActionResult List(int page = 1, int count = DefaultCount)
        {
            var list = Service.GetImageIds();

            page = page < 1 ? 1 : page;
            count = count < 0 ? DefaultCount : count;
            var model = list.Skip((page - 1) * count).Take(count).ToList();
            ViewBag.Paged = new StaticPagedList<Guid>(model, page, count, list.Count);
            return View();
        }

        [HttpPost]
        public ActionResult Delete(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Service.Delete<Image>(id.Value);
            return Json(id);
        }
    }
}
